const contentNode = document.getElementById('content');

class Login extends React.Component {
    render (){
        return(
            <LoginForm />
        )
    }
}

class LoginForm extends React.Component {
    constructor(){
        super();
        this.handleSubmit = this.handleSubmit.bind(this);
    }

    handleSubmit(e){
        e.preventDefault();
        var form = document.forms.loginForm;
        var username = form.username.value;
        var password = form.password.value;
        var data = {"username": username, "password": password}
        fetch("/api/login", {
            method: "POST",
            headers: {'Content-Type': 'application/json'},
            body: JSON.stringify(data),
        }).then(response=>{
            if (response.ok){
                response.json().then(result => {
                    if(result.status == 'error'){
                        console.log(result)
                        alert('登录错误：'+result.message);
                    }else if(result.status == 'ok'){
                        alert('登录成功：'+result.message);
                    }
                })
            }
        }).catch(err=>{
            console.log('Login Error:', err);
        })
    }

    render() {
        return (
            <form name="loginForm" onSubmit={this.handleSubmit}>
                <label htmlFor="username">用户名：</label>
                <input type="text" name="username" />
                <br/>
                <label htmlFor="password">密码:</label>
                <input type="password" name="password" />
                <br/>
                <input type="submit" value="登录" />
            </form>
        )

    }
}

ReactDOM.render(<Login />, contentNode);